import { BettingMethod, MatchType } from '@/enums'
import { BetType } from '@/types'

export const getMatchTime = ({ selections }: BetType) =>
	new Date(
		selections
			.slice()
			.sort(
				(a, b) => new Date(a.startEventDate).valueOf() - new Date(b.startEventDate).valueOf()
			)[0].startEventDate
	).valueOf()

export const compareByMatchTime = (a: BetType, b: BetType) => {
	const aLive = a.selections.some(({ isLive }) => isLive)
	const bLive = b.selections.some(({ isLive }) => isLive)
	if (aLive !== bLive) {
		return aLive ? -1 : 1
	}
	const aOutright = a.selections.every(({ eventType }) => eventType === MatchType.outright)
	const bOutright = b.selections.every(({ eventType }) => eventType === MatchType.outright)
	if (aOutright !== bOutright) {
		return bOutright ? -1 : 1
	}
	const aCombo = a.orderType === BettingMethod.combo
	const bCombo = b.orderType === BettingMethod.combo
	if (aCombo !== bCombo) {
		return bCombo ? -1 : 1
	}
	if (aLive) {
		return getMatchTime(b) - getMatchTime(a)
	} else {
		return getMatchTime(a) - getMatchTime(b)
	}
}

export const filterByBetTime = ({ createdAt }: BetType, dateRange: any) => {
	const fromDate = getFromDate(dateRange)
	const toDate = getToDate(dateRange)
	const betTS = new Date(createdAt).valueOf()
	return betTS >= fromDate && betTS <= toDate!
}

export const getFromDate = (dateRange: any) => {
	if (dateRange?.length > 0) {
		return dateRange[0]
	}
	return null
}

export const getToDate = (dateRange: any) => {
	if (dateRange?.length > 1) {
		const end = new Date(dateRange[1])
		return new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59).valueOf()
	}
	return null
}
